<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        title="拆包记录详情"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="$permission('unpackOrder:print')"
            @click="printCode()"
            >打印二维码</el-button
          >
          <el-button @click="_exportExcel">导出excel</el-button>
          <el-button @click="print()">打印</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <BasicInformation :info="infoList">
              <template v-slot:basic-invoiceNumber>
                <div
                  v-if="
                    infoList.data.invoiceNumberList &&
                    infoList.data.invoiceNumberList.length > 0
                  "
                >
                  <span
                    v-for="(item, index) in infoList.data.invoiceNumberList"
                    :key="index"
                  >
                    <a v-if="index <= 1">{{ item }}</a>
                    <span
                      v-if="
                        index < 1 && infoList.data.invoiceNumberList.length > 1
                      "
                      >,</span
                    >
                  </span>
                  <el-dropdown
                    v-if="infoList.data.invoiceNumberList.length > 2"
                  >
                    <span class="el-dropdown-link">
                      更多
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(item, index) in infoList.data
                            .invoiceNumberList"
                          :key="index"
                          >{{ item }}</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <span v-else>-</span>
              </template>
            </BasicInformation>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
              </PageTable>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <chose-printer :visible="printerInfo.visible" @callBack="printerCallBack" />
    <individual-details
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      v-model:query="individualInfo.query"
      :info="individualInfo.info"
    />
  </div>
</template>

<script setup name="stockUnpackDetail">
import PageTable from '../../../components/PageTable/index'

import {
  exportPrintQrCodeVO,
  getUnpackById,
  exportExcel,
  getUnpackDetailAll,
  getUnpackExportDetailCustomizeList,
  getUnapckPrint,
} from '@/api/unpack.js'
import IndividualDetails from './IndividualDetails'
import chosePrinter from '@/components/ChosePrinter/index'
import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: [Number, String],
  },
})
const infoList = ref({
  data: {},
  fieldList: [
    { label: '拆分单号', value: 'orderNo' },
    { label: '拆分人', value: 'createUserName' },
    { label: '拆分部门', value: 'deptName' },
    { label: '拆分仓库', value: 'depotName' },
    { label: '拆分时间', value: 'createTime' },
    { label: '备注', value: 'remark' },
  ],

  labelWidth: '130px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: getUnpackDetailAll,
  data: [],
  selections: [],
  summaryFieldList: [
    {
      value: 'qty',
      formatter: proxy.$fn.qtyFormatter,
    },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '打印二维码',
        event: printSingleQrCode,
        show: proxy.$permission('unpackOrder:print'),
        ifRender: ifRenderValue,
      },
      {
        label: '拆包入库明细信息',
        event: showDetail,
        show: proxy.$permission('unpackOrder:individualDetails'),
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  purchTemplateId: '',
})
const individualInfo = ref({
  visible: false,
  query: {},
  info: {},
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
watch(
  () => modifyInfo.value.visible,
  (value) => {
    if (!value) {
      getMain()
    }
  }
)

function showDetail(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  printerInfo.value.query = {
    exportDetailId: {
      columnName: 'export_detail_id',
      queryResource: 0,
      asTbName: 'unpack_store_detail',
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
  }
  printerInfo.value.info = row
  printerInfo.value.visible = true
}
function returnBack() {
  proxy.$emit('returnBack', false)
}
// 获取列表
function getList() {
  getUnpackExportDetailCustomizeList(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function getMain() {
  getUnpackById(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      infoList.value.data.invoiceNumberList = infoList.value.data.invoiceNumber
        ? infoList.value.data.invoiceNumber.indexOf(',') !== -1
          ? infoList.value.data.invoiceNumber.split(',')
          : [infoList.value.data.invoiceNumber]
        : []
      filterInfo.value.query.queryMap.orderId.value = props.id
      getList()
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//打印
function print() {
  fatchTemplateByCode({
    resourceCode: 'unpackOrder:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPirntData(temp)
    }
  })
}
function getPirntData(temp) {
  let params = {
    tableKey:
      'unpackProductDetailList-com.slip.spd.entity.vo.core.UnpackExportDetailVO',
    orderIds: [props.id],
  }
  getUnapckPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('unpackOrder:price')
      )
    }
  })
}
//批量打印
function printCode() {
  let ids = tableInfo.value.data.map((row) => row.id)
  exportPrintQrCodeVO(ids).then((resp) => {
    if (resp && resp.success) {
      printerInfo.value.visible = true
      printerInfo.value.data = resp.data
    }
  })
}
//打印单个二维码
function printSingleQrCode(row = undefined) {
  if (!row.qrCode) {
    proxy.$message({
      message: '没有生成二维码，不能打印',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }

  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = proxy.$fn.splitArr(row.groupConcatIds)
  } else {
    ids = [row.id]
  }
  if (ids.length > 0) {
    exportPrintQrCodeVO(ids).then((resp) => {
      if (resp && resp.success) {
        printerInfo.value.visible = true
        printerInfo.value.data = resp.data
      }
    })
  }
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
//导出excel
function _exportExcel() {
  exportExcel(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'unpackProductDetailList-com.slip.spd.entity.vo.core.UnpackExportDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      getMain()
    }
  })
}

let obj = {
  price: {
    label: '单价',
    value: 'price',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('unpackOrder:price'),
    show: false,
    hidden: true,
  },
  orderNo: {
    label: '单号',
    value: 'orderNo',
    type: 'column',
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('unpackOrder:price'),
    show: false,
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    componentType: 'price',
    type: 'column',
    value: 'defaultSupplierPrice',
    permission: !proxy.$permission('unpackOrder:price'),
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
</script>

<style scoped></style>
